package guoanmaker.operator.business.service;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import guoanmaker.operator.business.dao.PersonalAddressDao;
import guoanmaker.operator.business.model.OperatorCoupons;
import guoanmaker.operator.business.model.OperatorSendMesToCus;
import guoanmaker.operator.business.model.OperatorServerClass;
import guoanmaker.operator.business.model.OperatorSpace;
import guoanmaker.operator.business.model.OperatorUserSignIn;
import guoanmaker.operator.business.model.OperatorUserSignInActive;
import guoanmaker.operator.business.model.OperatorUserSignInConfiguration;
import guoanmaker.operator.business.model.OperatorUserSignInLog;
import guoanmaker.operator.business.model.OperatorUserSignInSwitch;
import guoanmaker.operator.business.model.PersonalAddress;
import guoanmaker.operator.business.model.PersonalUser;
import guoanmaker.operator.business.model.PersonalUserCoupon;
import guoanmaker.operator.business.model.PerviderDictionary;
import guoanmaker.operator.business.model.ReturnResult;
import guoanmaker.operator.business.modelnobind.OperatorUserSignInConfigurationRo;
import guoanmaker.operator.business.repository.OperatorCouponsRepository;
import guoanmaker.operator.business.repository.OperatorSendMesToCusRepositoy;
import guoanmaker.operator.business.repository.OperatorServerClassRepository;
import guoanmaker.operator.business.repository.OperatorUserSignInActiveRepository;
import guoanmaker.operator.business.repository.OperatorUserSignInConfigurationRepository;
import guoanmaker.operator.business.repository.OperatorUserSignInLogRepository;
import guoanmaker.operator.business.repository.OperatorUserSignInRepository;
import guoanmaker.operator.business.repository.OperatorUserSignInSwitchRepository;
import guoanmaker.operator.business.repository.PersonalAddressRepository;
import guoanmaker.operator.business.repository.PersonalUserCouponRepository;
import guoanmaker.operator.business.repository.PersonalUserRepository;
import guoanmaker.operator.business.repository.ProviderDictionaryRepository;

@Service
public class OperatorUserSignInService implements OperatorUserSignInServiceIntegerface {
	@Autowired
private OperatorUserSignInActiveRepository operatorUserSignInActiveRepository;
	@Autowired
	private OperatorUserSignInRepository operatorUserSignInRepository;
	@Autowired
	private PersonalUserRepository personalUserRepository;
	@Autowired
	private OperatorUserSignInLogRepository operatorUserSignInLogRepository;
	@Autowired
	private OperatorUserSignInConfigurationRepository operatorUserSignInConfigurationRepository;
	@Autowired
	private OperatorUserSignInSwitchRepository operatorUserSignInSwitchRepository;
	@Autowired
	private  OperatorCouponsRepository operatorCouponsRepository;
	@Autowired
	private  PersonalUserCouponRepository personalUserCouponRepository;
	@Autowired
	private PersonalAddressRepository personalAddressRepository;
	@Autowired
	private OperatorSendMesToCusRepositoy operatorSendMesToCusRepositoy;
	@Autowired
	private  ProviderDictionaryRepository providerDictionaryRepository;
	@Autowired
	private OperatorServerClassRepository operatorServerClassRepository;
	 @PersistenceContext
		private EntityManager manager;
	@Override
	@Transactional
	public Map selectUserSignIn(String userid) {
		Map<String , Object> remap=new HashMap<String ,Object>();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		Date time=null;
		int a=0;
		 try {
			time= sdf.parse(sdf.format(new Date()));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		List<OperatorUserSignInActive> operatorUserSignInActive=operatorUserSignInActiveRepository.selectByOperatorUserSignInActive(1);
		if(operatorUserSignInActive.size()>0){
		String jpql="select u from OperatorUserSignInLog u where u.perUserId=:perUserId and u.signInActiveId=:signInActiveId and u.createDate=:createDate";
		Query query = manager.createQuery(jpql);
		query.setParameter("perUserId", userid);
		query.setParameter("signInActiveId", operatorUserSignInActive.get(0).getId());
		query.setParameter("createDate", time);
		List<OperatorUserSignInLog> signs=query.getResultList();
		
		if(signs.size()<=0){
	
		String detail="";
		String  pType="0";//0是未中奖 1是优惠券 2是实物
		String  fullmoney="";
		String submoney="";
		Date endDate=null;
		String picUrl="";
		String consServerName="";
		PersonalUser personalUser=null;
		OperatorUserSignIn operatorUserSignIn=null;
		if(operatorUserSignInActive.size()>0){
			operatorUserSignIn=operatorUserSignInRepository.selectByOperatorUserSignIn(userid,operatorUserSignInActive.get(0).getId());
			personalUser=personalUserRepository.findOne(userid);
			Date date=new Date();
			if(operatorUserSignIn!=null){
				
				operatorUserSignIn.setSignInNum(operatorUserSignIn.getSignInNum()+1);
				operatorUserSignIn.setSignInDatetime(date);
			}else{
				operatorUserSignIn=new OperatorUserSignIn();
				operatorUserSignIn.setSignInNum(1);
				
				
				operatorUserSignIn.setSignInDatetime(date);
				operatorUserSignIn.setPerUserId(userid);
				if(personalUser!=null){
					operatorUserSignIn.setPerUserPhone(personalUser.getUsername());
					operatorUserSignIn.setPerUserName(personalUser.getNickname());
				}
				operatorUserSignIn.setSignInAcId(operatorUserSignInActive.get(0).getId());
				
			}
			
			
			List<OperatorUserSignInConfiguration> operatorUserSignInConfigurations=operatorUserSignInConfigurationRepository.selectByOperatorUserSignInConfiguration(operatorUserSignInActive.get(0).getId());
			if(operatorUserSignInConfigurations.size()>0){
				
				for(OperatorUserSignInConfiguration sign:operatorUserSignInConfigurations){
					if(sign.getDays()==operatorUserSignIn.getSignInNum()){
						
						if(sign.getPrizeType()==1){
							// 变更 优惠券发送数量
							operatorCouponsRepository.updateBeensentByid(sign.getCouponsId());
							// 向用户下 添加 优惠券信息
							PersonalUserCoupon personalUserCoupon = new PersonalUserCoupon();

							personalUserCoupon.setIsUsed("0");
							personalUserCoupon.setOcId(sign.getCouponsId());
							personalUserCoupon.setUserId(userid);
							OperatorCoupons coupons=operatorCouponsRepository.findOne(sign.getCouponsId());
							if (coupons.getDatetype().equals("1") == true) {
								personalUserCoupon.setExpiredDate(coupons.getEndofdate());
							} else {
								Date expiredDate = new Date();
								Calendar ca = Calendar.getInstance();
								ca.add(Calendar.DATE, coupons.getValidityPeriod());// num为增加的天数，可以改变的
								expiredDate = ca.getTime();
								personalUserCoupon.setExpiredDate(expiredDate);
							}
							personalUserCoupon.setStart_date(new Date());
							personalUserCouponRepository.save(personalUserCoupon);
							detail="满"+coupons.getFullamount()  +"减"+coupons.getSubamount() +"券";
							if(operatorUserSignIn.getPrizeList()==null){
								operatorUserSignIn.setPrizeList(detail);
							}else{
								operatorUserSignIn.setPrizeList(operatorUserSignIn.getPrizeList()+","+detail);
							}
							if(!coupons.getServerid().equals("0")){
							OperatorServerClass operatorServerClass=operatorServerClassRepository.findOne(coupons.getServerid());
							consServerName="仅限"+operatorServerClass.getServerName()+"类使用";
							}else{
								consServerName="全平台均可使用";
							}
							pType=sign.getPrizeType()+"";
							fullmoney=coupons.getFullamount()+"";
							submoney=coupons.getSubamount()+"";
							endDate=personalUserCoupon.getExpiredDate();
							 OperatorSendMesToCus od=new OperatorSendMesToCus();
							 if(personalUser.getEmail()!=null){
							 od.setEmail(personalUser.getEmail());}
							 od.setPhone(personalUser.getUsername());
							 od.setSendWay("13");
							
							 od.setMesContent("恭喜获得"+detail);
							 od.setMesTitle("签到中奖");
							 od.setSendTime(new Date());
							 od.setSendStatus("1");//1  未读  2已读
						 PerviderDictionary perviderDictionary= providerDictionaryRepository.findOne("13");
							 od.setMesType(perviderDictionary.getDictName());
							 operatorSendMesToCusRepositoy.save(od);
							break;
						}else if(sign.getPrizeType()==2){
							detail=sign.getPrizeName();
							if(operatorUserSignIn.getPrizeList()==null){
								operatorUserSignIn.setPrizeList(detail);
							}else{
								operatorUserSignIn.setPrizeList(operatorUserSignIn.getPrizeList()+","+detail);
							}
							pType=sign.getPrizeType()+"";
							picUrl=sign.getPrizePicUrl();
							 OperatorSendMesToCus od=new OperatorSendMesToCus();
							 od.setEmail(personalUser.getEmail());
							 od.setPhone(personalUser.getUsername());
							 od.setSendWay("13");
							
							 od.setMesContent("恭喜获得"+detail);
							 od.setMesTitle("签到中奖");
							 od.setSendTime(new Date());
							 od.setSendStatus("1");//1  未读  2已读
						 PerviderDictionary perviderDictionary= providerDictionaryRepository.findOne("13");
							 od.setMesType(perviderDictionary.getDictName());
							 operatorSendMesToCusRepositoy.save(od);
							break;
						}
						
						
						
					}
					
					
					}
				
				
				}
			
			OperatorUserSignIn	signinuser=operatorUserSignInRepository.save(operatorUserSignIn);
			
			OperatorUserSignInLog operatorUserSignInLog=new OperatorUserSignInLog();
			
			operatorUserSignInLog.setSignNumtoDay(signinuser.getSignInNum());
			operatorUserSignInLog.setCreateDate(time);
			operatorUserSignInLog.setPerUserId(userid);
			operatorUserSignInLog.setSignInActiveId(operatorUserSignInActive.get(0).getId());
			operatorUserSignInLog.setPrizeName(detail);
			operatorUserSignInLogRepository.save(operatorUserSignInLog);
			
		}
		remap.put("days", operatorUserSignIn.getSignInNum());
		remap.put("detail", detail);
		remap.put("pType", pType);
		remap.put("fullmoney", fullmoney);
		remap.put("submoney", submoney);
		remap.put("endDate", endDate);
		remap.put("picUrl", picUrl);
		remap.put("consServerName", consServerName);
		a=1;//签到成功
		}else{
			a=3;//今天已经签到
		}
		}else{
			a=2;//没有开始的活动
		}
		remap.put("a", a);
		return remap;
	}
	
	  @Override
	    @Transactional
	    public OperatorUserSignInConfiguration saveOperatorUserSignInConfiguration(OperatorUserSignInConfiguration operatorUserSignInConfiguration) {
	        return operatorUserSignInConfigurationRepository.save(operatorUserSignInConfiguration);
	    }
	  
	  @Transactional
	  public void delectAllUserSignInConfiguration(String signActiveId){
		  String jpql="delete  from OperatorUserSignInConfiguration u where u.signActiveId=:signActiveId";
		  Query query2=manager.createQuery(jpql);//查询签到服务配置
		  query2.setParameter("signActiveId", signActiveId);
			query2.executeUpdate();
		  
	  }

	@Override
	public List<OperatorUserSignInConfiguration> selectOperatorUserSignInConfigurationlist() {
		// TODO Auto-generated method stub
		return operatorUserSignInConfigurationRepository.findAll();
	}

	@Override
	public OperatorUserSignInActive saveOperatorUserSignInActive(OperatorUserSignInActive operatorUserSignInActive) {
		// TODO Auto-generated method stub
		return operatorUserSignInActiveRepository.save(operatorUserSignInActive);
	}

	@Override
	public Map selectOperatorUserSignInActiveList(Integer page,Integer size,String status) {
		// TODO Auto-generated method stub
		Map<String , Object> remap=new HashMap<String ,Object>();
		List<OperatorUserSignInActive> acs=null;
		Page<OperatorUserSignInActive> signactives=null;
		if(status!=null&&!status.equals("")){
			acs=operatorUserSignInActiveRepository.selectByOperatorUserSignInActiveBystatus();
			remap.put("count", acs.size());
			signactives=operatorUserSignInActiveRepository.findOperatorUserSignInActiveBypageBystatus(new PageRequest(page, size, new Sort(Sort.Direction.DESC, "createDate")));
			
		}else{
			 acs=operatorUserSignInActiveRepository.findAll();
				remap.put("count", acs.size());
				signactives=operatorUserSignInActiveRepository.findByOperatorUserSignInActiveBypage(new PageRequest(page, size, new Sort(Sort.Direction.DESC, "createDate")));
		}
		
		for(OperatorUserSignInActive signActive:signactives){
			List<OperatorUserSignIn> logs=operatorUserSignInRepository.findByOperatorUserSignInList(signActive.getId());
			signActive.setSignNum(logs.size()+"");
			if(signActive.getSignInStatus()==0){
				signActive.setStatusName("未开始");
			}
			if(signActive.getSignInStatus()==1){
				signActive.setStatusName("进行中");
			}
			if(signActive.getSignInStatus()==2){
				signActive.setStatusName("已结束");
			}
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd");
		    String createString = formatter.format(signActive.getSignInCreateTime());
		    String endString = formatter.format(signActive.getSignInEndTime());
			
			signActive.setActiveDate(createString+"-"+endString);
			
			
		}
		remap.put("signactives", signactives);
		return remap;
	}

	@Override
	public Map selectOperatorUserSignInList(Integer page, Integer size,String signactivId) {
		Map<String , Object> remap=new HashMap<String ,Object>();
		List<OperatorUserSignIn> OperatorUserSignIns=null;
		Page<OperatorUserSignIn> signpages=null;
		long signcount=0;
		if(signactivId!=null&&!signactivId.equals("")){
		 OperatorUserSignIns=operatorUserSignInRepository.findByOperatorUserSignInList(signactivId);
		  signpages=operatorUserSignInRepository.findByOperatorUserSignInBypage(new PageRequest(page, size, new Sort(Sort.Direction.DESC, "signInNum")),signactivId);
		  for(OperatorUserSignIn sign:signpages){
			  String jpql1="select new guoanmaker.operator.business.dao.PersonalAddressDao(a.name,a.address,a.telephone,a.isdefault,u.id)from PersonalAddress a "
						+ "left join a.user u where u.id=:id and a.isdefault=:isdefault";
				Query query1 = manager.createQuery(jpql1);
				query1.setParameter("id", sign.getPerUserId());
				query1.setParameter("isdefault","1");
				PersonalAddressDao personalAddressDao=null;
				if(query1.getResultList().size()>0){
			personalAddressDao=(PersonalAddressDao) query1.getResultList().get(0);
				}
			  if(personalAddressDao!=null&&!personalAddressDao.equals("")){
			  sign.setAddress(personalAddressDao.getAddress());
			  sign.setAddname(personalAddressDao.getName());
			  sign.setAddphone(personalAddressDao.getTelephone());
			  }
		  }
		  signcount=OperatorUserSignIns.size();
		}else{
			List<OperatorUserSignInActive> operatorUserSignInActive=operatorUserSignInActiveRepository.selectByOperatorUserSignInActive(1);
			if(operatorUserSignInActive.size()!=0){
			OperatorUserSignIns=operatorUserSignInRepository.findByOperatorUserSignInList(operatorUserSignInActive.get(0).getId());
			 signpages=operatorUserSignInRepository.findByOperatorUserSignInBypage(new PageRequest(page, size, new Sort(Sort.Direction.DESC, "signInNum")),operatorUserSignInActive.get(0).getId());
			 for(OperatorUserSignIn sign:signpages){
				  String jpql1="select new guoanmaker.operator.business.dao.PersonalAddressDao(a.name,a.address,a.telephone,a.isdefault,u.id)from PersonalAddress a "
							+ "left join a.user u where u.id=:id and a.isdefault=:isdefault";
					Query query1 = manager.createQuery(jpql1);
					query1.setParameter("id", sign.getPerUserId());
					query1.setParameter("isdefault","1");
					PersonalAddressDao personalAddressDao=null;
					if(query1.getResultList().size()>0){
				personalAddressDao=(PersonalAddressDao) query1.getResultList().get(0);
					}
				  if(personalAddressDao!=null&&!personalAddressDao.equals("")){
				  sign.setAddress(personalAddressDao.getAddress());
				  sign.setAddname(personalAddressDao.getName());
				  sign.setAddphone(personalAddressDao.getTelephone());
				  }
			  }
			 signcount=OperatorUserSignIns.size();
			}
		}
		remap.put("count", signcount);
		remap.put("signpages", signpages);
		return remap;
	}
	
	@Override
	public Map selectOperatorAcAndCon(String id) {
		// TODO Auto-generated method stub
		Map<String , Object> remap=new HashMap<String ,Object>();
		OperatorUserSignInActive operatorUserSignInActive=operatorUserSignInActiveRepository.findOne(id);
		List<OperatorUserSignInConfiguration> operatorUserSignInConfigurations=operatorUserSignInConfigurationRepository.selectByOperatorUserSignInConfiguration(id);
		remap.put("operatorUserSignInActive", operatorUserSignInActive);
		remap.put("operatorUserSignInConfigurations", operatorUserSignInConfigurations);
		return remap;
	}

	@Override
	public List<OperatorUserSignInSwitch> selectOperatorUserSignInSwitch() {
		// TODO Auto-generated method stub
		return operatorUserSignInSwitchRepository.findAll();
		
	}

	@Override
	public OperatorUserSignInSwitch saveOperatorUserSignInSwitch(OperatorUserSignInSwitch operatorUserSignInSwitch) {
		// TODO Auto-generated method stub
		return operatorUserSignInSwitchRepository.save(operatorUserSignInSwitch);
	}

	@Override
	public Page<OperatorUserSignIn> selectOperatorUserSignInallList() {
		// TODO Auto-generated method stub
		List<OperatorUserSignInActive> operatorUserSignInActive=operatorUserSignInActiveRepository.selectByOperatorUserSignInActive(1);
		return operatorUserSignInRepository.findByOperatorUserSignInBypage(new PageRequest(0,15, new Sort(Sort.Direction.DESC, "signInNum")),operatorUserSignInActive.get(0).getId());
		/*return operatorUserSignInRepository.findByOperatorUserSignInList(operatorUserSignInActive.get(0).getId());*/
		
	}

	@Override
	public Map selectSignInInitialize(String usrerid) {
		Map<String , Object> remap=new HashMap<String ,Object>();
		List<OperatorUserSignInActive> operatorUserSignInActive=operatorUserSignInActiveRepository.selectByOperatorUserSignInActive(1);
		List<OperatorUserSignInConfiguration> operatorUserSignInConfigurations=null;
		if(operatorUserSignInActive.size()!=0){
		operatorUserSignInConfigurations=operatorUserSignInConfigurationRepository.selectByOperatorUserSignInConfiguration(operatorUserSignInActive.get(0).getId());
		}
		List<OperatorUserSignInLog> logs=null;
		if(usrerid!=null&&!usrerid.equals("")){
			logs=operatorUserSignInLogRepository.findByUserSignInLogsByuser(operatorUserSignInActive.get(0).getId(), usrerid);
			
		}
		
		remap.put("logs", logs);
		List<OperatorUserSignInSwitch> switchs=operatorUserSignInSwitchRepository.findAll();
		String jpql1="select new guoanmaker.operator.business.dao.PersonalAddressDao(a.name,a.address,a.telephone,a.isdefault,u.id)from PersonalAddress a "
				+ "left join a.user u where u.id=:id and a.isdefault=:isdefault";
		Query query1 = manager.createQuery(jpql1);
		query1.setParameter("id", usrerid);
		query1.setParameter("isdefault","1");
		PersonalAddressDao personalAddressDao=null;
		if(query1.getResultList().size()>0){
			personalAddressDao=(PersonalAddressDao) query1.getResultList().get(0);
		}
		remap.put("personalAddress", personalAddressDao);
		/* PersonalAddress personalAddress=  personalAddressRepository.findByCode(usrerid);
		 remap.put("personalAddress", personalAddress);*/
		remap.put("operatorUserSignInActive", operatorUserSignInActive.get(0));
		remap.put("operatorUserSignInConfigurations", operatorUserSignInConfigurations);
		remap.put("switchs", switchs);
		String jpql="select u from OperatorUserSignInLog u";
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		   Calendar c = Calendar.getInstance();    
	        c.add(Calendar.MONTH, 0);
	        c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天 
	        String first = format.format(c.getTime());
	        Date ff=null;
	        Date ll=null;
	        try {
				ff=format.parse(first);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        Calendar calendar = Calendar.getInstance();
	        calendar.add(Calendar.MONTH, 1);
	        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH)); 
	        String last = format.format(calendar.getTime());
	        try {
				ll=format.parse(last);
				System.out.println(ll);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		System.out.println(first+"33");
		jpql+=" where u.createDate >= :ff ";
		
		jpql+=" and u.createDate < :ll ";
		jpql+=" and u.perUserId =:perUserId ";
		jpql+=" and u.signInActiveId =:signInActiveId ";
		jpql+=" order by  signNumtoDay asc";
		Query query = manager.createQuery(jpql);
		query.setParameter("ff", ff);
		query.setParameter("ll", ll);
		query.setParameter("perUserId", usrerid);
		query.setParameter("signInActiveId", operatorUserSignInActive.get(0).getId());
		List<OperatorUserSignInLog> OperatorUserSignInLogs=query.getResultList();
		
		StringBuffer sb = new StringBuffer();
		Map<String,Object> remaps=new HashMap<String ,Object>();
		for(OperatorUserSignInLog signlogs:OperatorUserSignInLogs){
			int a=signlogs.getCreateDate().getDate();
			
			
			sb.append(a);
			sb.append(",");
			signlogs.setDay(a);
			
			
		}
		/*StringBuffer sbs = new StringBuffer();*/
	/*	int logsize=OperatorUserSignInLogs.size();
		int signDay=0;
		int creaday=0;
		if(logsize>0){
			OperatorUserSignInLog signlog=OperatorUserSignInLogs.get(logsize-1);
		signDay=signlog.getSignNumtoDay();
		creaday=signlog.getCreateDate().getDate();
		}
		List<OperatorUserSignInConfigurationRo> ros=new ArrayList<OperatorUserSignInConfigurationRo>();
		for(OperatorUserSignInConfiguration cinfig:operatorUserSignInConfigurations){
			int cc=0;
			if(signDay<cinfig.getDays()){
				cc=cinfig.getDays()-signDay;
				int a=new Date().getDate();
				int ss=0;
				if(creaday!=a){
					ss=a+cc-1;
				}else{
					ss=a+cc;
				}
				
				sbs.append(ss);
				sbs.append(",");
				OperatorUserSignInConfigurationRo ro=new OperatorUserSignInConfigurationRo();
				ro.setCouponsId(cinfig.getCouponsId());
				ro.setDays(cinfig.getDays());
				ro.setEndofdate(cinfig.getEndofdate());
				ro.setFullamount(cinfig.getFullamount());
				ro.setPrizeName(cinfig.getPrizeName());
				ro.setPrizePicUrl(cinfig.getPrizePicUrl());
				ro.setPrizeType(cinfig.getPrizeType());
				ro.setServerName(cinfig.getServerName());
				ro.setSignActiveId(cinfig.getSignActiveId());
				ro.setSubamount(cinfig.getSubamount());
				ro.setTail(cinfig.getTail());
				ro.setPrizeDate(ss);
				ros.add(ro);
			}
		}
		
		System.out.println(ros+"以后签到中奖");
		remap.put("ros", ros);*/
		remap.put("day", sb);
		
		remap.put("OperatorUserSignInLogs", OperatorUserSignInLogs);
		return remap;
	}

	@Override
	public List<OperatorUserSignInActive> selectOperatorUserSignAcByDate(Date signInCreateTime) {
		List<OperatorUserSignInActive> actives=operatorUserSignInActiveRepository.findOperatorUserSignInActiveBycreateDate();
		
		/*String jpql="select u from OperatorUserSignInActive u ";
		jpql+=" where u.signInCreateTime < :signInCreateTime ";
		Query query = manager.createQuery(jpql);
		query.setParameter("signInCreateTime", signInCreateTime);
		List<OperatorUserSignInActive> OperatorUserSignInAcs=query.getResultList();*/
		// TODO Auto-generated method stub
		return actives;
	}

	@Override
	public Integer findSignInNumByUserIdAndActId(String userId, String actId) {
		OperatorUserSignIn operatorUserSign = operatorUserSignInRepository.selectByOperatorUserSignIn(userId, actId);
		if(operatorUserSign == null){
			return null;
		}
		return operatorUserSign.getSignInNum();
	}
	/**
	 * 根据userID 查询 是否有默认地址 有则返回 
	 */
	@Override
	public PersonalAddressDao selectDefaultAddress(String userid) {
		String jpql1="select new guoanmaker.operator.business.dao.PersonalAddressDao(a.name,a.address,a.telephone,a.isdefault,u.id)from PersonalAddress a "
				+ "left join a.user u where u.id=:id and a.isdefault=:isdefault";
		Query query1 = manager.createQuery(jpql1);
		query1.setParameter("id", userid);
		query1.setParameter("isdefault","1");
		PersonalAddressDao personalAddressDao=null;
		if(query1.getResultList().size()>0){
			personalAddressDao=(PersonalAddressDao) query1.getResultList().get(0);
		}
		return personalAddressDao;
	}
	/**
	 * 保存默认地址
	 */
	@Override
	@Transactional
	public ReturnResult saveDefaultAddress(PersonalAddress personalAddress) {
		ReturnResult returnResult = new ReturnResult();
		if(personalAddress ==null) {
			returnResult.setKey("error");
			returnResult.setValue("保存失败");
		}else {
			PersonalAddress newPersonalAddress = personalAddressRepository.save(personalAddress);
			if (newPersonalAddress != null) {
				returnResult.setKey("success");
				returnResult.setValue(newPersonalAddress.getAddress());
			} else {
				returnResult.setKey("error");
				returnResult.setValue("保存失败");
			}
		}
		
		return returnResult;
	}
	@Transactional
	@Override
	public Workbook exportHistoricalSignInActivity(String activityId) {
		Workbook wb = new HSSFWorkbook();
		Sheet sheet = wb.createSheet("签到列表");
		Row header = sheet.createRow(0);
		header.createCell(0).setCellValue("排名");
		header.createCell(1).setCellValue("用户昵称");
		header.createCell(2).setCellValue("用户手机");
		header.createCell(3).setCellValue("签到累计天数");
		header.createCell(4).setCellValue("签到时间");
		header.createCell(5).setCellValue("奖品名称");
		header.createCell(6).setCellValue("邮寄地址");
		header.createCell(7).setCellValue("收货人");
		header.createCell(8).setCellValue("收货人联系电话");
		
		List<OperatorUserSignIn> operatorUserSignIns = null;
		if (activityId != null &&! activityId.equals("")) {
			operatorUserSignIns = operatorUserSignInRepository.findByOperatorUserSignInList(activityId);
		}else {
			List<OperatorUserSignInActive> operatorUserSignInActive=operatorUserSignInActiveRepository.selectByOperatorUserSignInActive(1);
			if(operatorUserSignInActive.size()!=0){
				operatorUserSignIns = operatorUserSignInRepository.findByOperatorUserSignInList(operatorUserSignInActive.get(0).getId());
			}
		}
		if (operatorUserSignIns != null && operatorUserSignIns.size() >0) {
			OperatorUserSignIn operatorUserSignIn = null;
			for (int i = 0; i < operatorUserSignIns.size(); i++) {
				operatorUserSignIn = operatorUserSignIns.get(i);
				String jpql1="select new guoanmaker.operator.business.dao.PersonalAddressDao(a.name,a.address,a.telephone,a.isdefault,u.id)from PersonalAddress a "
						+ "left join a.user u where u.id=:id and a.isdefault=:isdefault";
				Query query1 = manager.createQuery(jpql1);
				query1.setParameter("id", operatorUserSignIn.getPerUserId());
				query1.setParameter("isdefault","1");
				PersonalAddressDao personalAddressDao=null;
				if (query1.getResultList().size() >0) {
					personalAddressDao = (PersonalAddressDao)query1.getResultList().get(0);
				}
				if (personalAddressDao != null && !"".equals(personalAddressDao)) {
					Row dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
					dataRow.createCell(0).setCellValue(i+1+"");
					dataRow.createCell(1).setCellValue(operatorUserSignIn.getPerUserName() != null ? operatorUserSignIn.getPerUserName() : "");
					dataRow.createCell(2).setCellValue(operatorUserSignIn.getPerUserPhone() != null ? operatorUserSignIn.getPerUserPhone() : "");
					dataRow.createCell(3).setCellValue(String.valueOf(operatorUserSignIn.getSignInNum()) != null ? String.valueOf(operatorUserSignIn.getSignInNum()) : "");
					dataRow.createCell(4).setCellValue(operatorUserSignIn.getSignInDatetime());
					dataRow.createCell(5).setCellValue(operatorUserSignIn.getPrizeList() != null ? operatorUserSignIn.getPrizeList() : "");
					dataRow.createCell(6).setCellValue(personalAddressDao.getAddress() != null ? personalAddressDao.getAddress() : "");
					dataRow.createCell(7).setCellValue(personalAddressDao.getName() != null ? personalAddressDao.getName() : "");
					dataRow.createCell(8).setCellValue(personalAddressDao.getTelephone() != null ? personalAddressDao.getTelephone() : "");
					
				}
			}
			
			
			
		}
		return wb;
	}
	 /**
	  * 
	     * @Title: exportHistoricalSignIn
	     * @Description: 导出签到列表前端用
	     * @param @param signactivId
	     * @return AjaxJson  
	     * @throws
	  */
	@Override
	public List<OperatorUserSignIn> exportHistoricalSignIn(String signactivId) {
		List<OperatorUserSignIn> operatorUserSignIns = null;
		if (signactivId != null &&! signactivId.equals("")) {
			operatorUserSignIns = operatorUserSignInRepository.findByOperatorUserSignInList(signactivId);
		}else {
			List<OperatorUserSignInActive> operatorUserSignInActive=operatorUserSignInActiveRepository.selectByOperatorUserSignInActive(1);
			if(operatorUserSignInActive.size()!=0){
				operatorUserSignIns = operatorUserSignInRepository.findByOperatorUserSignInList(operatorUserSignInActive.get(0).getId());
			}
		}
		if (operatorUserSignIns != null && operatorUserSignIns.size() >0) {
			OperatorUserSignIn operatorUserSignIn = null;
			for (int i = 0; i < operatorUserSignIns.size(); i++) {
				operatorUserSignIn = operatorUserSignIns.get(i);
				operatorUserSignIn.setPmIndex(i+1+"");
				String jpql1="select new guoanmaker.operator.business.dao.PersonalAddressDao(a.name,a.address,a.telephone,a.isdefault,u.id)from PersonalAddress a "
						+ "left join a.user u where u.id=:id and a.isdefault=:isdefault";
				Query query1 = manager.createQuery(jpql1);
				query1.setParameter("id", operatorUserSignIn.getPerUserId());
				query1.setParameter("isdefault","1");
				PersonalAddressDao personalAddressDao=null;
				if (query1.getResultList().size() >0) {
					personalAddressDao = (PersonalAddressDao)query1.getResultList().get(0);
				}
				if (personalAddressDao != null && !"".equals(personalAddressDao)) {
					operatorUserSignIn.setAddress(personalAddressDao.getAddress());
					operatorUserSignIn.setAddname(personalAddressDao.getName());
					operatorUserSignIn.setAddphone(personalAddressDao.getTelephone());
					
				}
			}
			
			
		}
		return operatorUserSignIns;
	}
}
